package com.flca.dbs.jpa;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.flca.frw.dao.Dao;
import com.flca.frw.dao.DaoFactory;
import com.flca.frw.dao.RegisterDatabase;

public class JpaDaoFactory implements DaoFactory {

	private static Logger logger = LoggerFactory.getLogger(JpaDaoFactory.class);

	private RegisterDatabase registerDbs; 
	private EntityManagerFactory emf;
	
	
	public JpaDaoFactory() {
		super();
	}

	
	@Override
	public void register(RegisterDatabase aRegisterDbs) {
		this.registerDbs = aRegisterDbs;
	}


	public Dao build() {
		try {
			logger.info("Creating new Entitymanager " + registerDbs.getUrl());
			EntityManager em = emf().createEntityManager();
			return new JpaDaoImpl(em);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private EntityManagerFactory emf() {
		if (this.emf == null) {
			try {
				this.emf = Persistence.createEntityManagerFactory(registerDbs.getUnitName());
			} catch (Throwable t) {
				logger.error("error creating EntityManagerFactory " + t);
				throw new RuntimeException(t);
			}
		}

		return this.emf;
	}
	
}
